import {observable as o, computed as c, action as a} from 'mobx';
import _ from 'lodash';
import axios from 'core/axios';
import RootStore from 'core/Store.js';
import request from 'core/request.js';
import Im from 'immutable';


class Store extends RootStore {
    constructor(args) {
        super(args);
    }

    @o userPassword = '';
    @o userName = '';
    @o loading = false;


    will() {
    }

    enterKey(e, isPhoneEnter) {
        if (e.which === 13) {
            this.login(isPhoneEnter);
        }
    }

    inputUserName(v) {
        this.userName = v;
    }

    inputPassword(v) {
        this.userPassword = v;
    }

    login(isPhoneEnter) {
        if (!this.userName || (this.userName && !this.userName.trim())) {
            !isPhoneEnter && this.stores.Message.showMessage(3, '请输入账号、手机号');
            return;
        }
        if (!this.userPassword || (this.userPassword && !this.userPassword.trim())) {
            !isPhoneEnter && this.stores.Message.showMessage(3, '请输入密码');
            return;
        }
        this.loading = true;
        request({
            method: 'post', url: $$.api('login'), data: {
                password: this.userPassword,
                userName: this.userName
            }
        }).then(res => {
            this.loading = false;
            $$.utils.setCookie('sessionId', res.data.token, $$.SEM.LOGIN_STATUS_DAY_TIME);
            global.window.location.href = $$.url('home');
        }).catch(err => {
            this.loading = false;
            this.stores.Message.fire('message', {type: $$.SEM.ERROR_TEXT, text: err.message});
        });
    }

    mount() {
        if ($$.utils.getCookie('sessionId')) {
            global.window.location.href = $$.url('home');
        }
    }
}

export default Store;